package zcxn.microService.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;

import org.yaml.snakeyaml.Yaml;


import com.google.gson.Gson;

public class YamlPropertiesUtil {
	
//	static final String modbuscmdPath = "./modbusComm.yaml";
	static final String modbuscmdPath = "E:/Eclipse-Workspace/workspace/BuildMicroService/src/main/resources/modbusComm.yaml";
	
	
	public static void main(String[] args) throws IOException {
		Map<String, Object> map=yamlDataToMap(modbuscmdPath);
        System.out.println(map);
	}
	
//	yaml文件转换字符串
	public static String yamlToJson(String file) {
		Gson gs=new Gson();
        Map<String, Object> loaded = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            Yaml yaml = new Yaml();
            loaded = (Map<String, Object>) yaml.load(fis);
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
        return gs.toJson(loaded);
    }

	
	
	/**
	 * 加载Global中的需要配置的参数(可变的) 
	 * properies文件转换map
	 * 
	 * @param globalPro
	 * @return
	 * @throws IOException
	 */
	public static Map<String, Object> loadProPerties(String globalPropath) throws IOException {
		Properties properties = new Properties();
		InputStream in = Object.class.getResourceAsStream(globalPropath);
		properties.load(in);
		Map<String, Object> map = new HashMap<String, Object>();
		Set<Entry<Object, Object>> entrySet = properties.entrySet();
		Iterator<Entry<Object, Object>> iterator = entrySet.iterator();
		while (iterator.hasNext()) {
			Entry<Object, Object> next = iterator.next();
			String key = (String) next.getKey();
			Object val = next.getValue();
			map.put(key, val);
		}
		return map;
	}

	
	/**
	 * 将yaml文件转为map
	 * 
	 * @param yamlpath
	 * @return
	 * @throws FileNotFoundException
	 */
	public static Map<String, Object> yamlDataToMap(String yamlpath) throws FileNotFoundException {
		Yaml yaml = new Yaml();
		File file = new File(yamlpath);
		InputStream is = new FileInputStream(file);
		Object load = yaml.load(is);
		String dump = yaml.dump(load);
		@SuppressWarnings("unchecked")
		Map<String, Object> map = (Map<String, Object>) yaml.load(dump);
		return map;
	}
}
